package com.zealfi.wk.netty.udp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * Created by kuan at 2018-06-14 下午 5:33
 */
public class LogEventEncoder extends MessageToMessageEncoder<LogEvent> {
    private final InetSocketAddress address;

    public LogEventEncoder(InetSocketAddress address) {
        this.address = address;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, LogEvent msg, List<Object> out) throws Exception {
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes(msg.getLogfile().getBytes(CharsetUtil.UTF_8));
        buffer.writeByte(LogEvent.SEPARATOR);
        buffer.writeBytes(msg.getMsg().getBytes(CharsetUtil.UTF_8));

        out.add(new DatagramPacket(buffer, address));
    }
}
